#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from database import db_manager

def fix_database_structure():
    """修复数据库表结构"""
    try:
        print("开始修复数据库表结构...")
        
        # 1. 更新角色表的职业枚举，添加'刺客'和'牧师'
        print("\n1. 更新角色表职业枚举...")
        alter_enum_sql = """
        ALTER TABLE characters 
        MODIFY COLUMN character_class ENUM('战士','法师','弓箭手','盗贼','刺客','牧师') 
        NOT NULL DEFAULT '战士' COMMENT '职业'
        """
        
        db_manager.execute_update(alter_enum_sql)
        print("职业枚举更新成功")
        
        # 2. 添加缺失的字段（如果需要）
        print("\n2. 检查并添加缺失字段...")
        
        # 检查是否有char_class字段，如果没有则添加（作为character_class的别名）
        try:
            # 添加hp, mp, attack, defense, speed字段（如果不存在）
            missing_fields = [
                ("hp", "INT NOT NULL DEFAULT 100 COMMENT '生命值'"),
                ("mp", "INT NOT NULL DEFAULT 50 COMMENT '魔法值'"),
                ("attack", "INT NOT NULL DEFAULT 10 COMMENT '攻击力'"),
                ("defense", "INT NOT NULL DEFAULT 5 COMMENT '防御力'"),
                ("speed", "INT NOT NULL DEFAULT 8 COMMENT '速度'"),
                ("status", "ENUM('idle','battle','offline') NOT NULL DEFAULT 'idle' COMMENT '角色状态'"),
                ("last_active", "TIMESTAMP NULL COMMENT '最后活跃时间'")
            ]
            
            for field_name, field_def in missing_fields:
                try:
                    add_field_sql = f"ALTER TABLE characters ADD COLUMN {field_name} {field_def}"
                    db_manager.execute_update(add_field_sql)
                    print(f"添加字段 {field_name} 成功")
                except Exception as e:
                    if "Duplicate column name" in str(e):
                        print(f"字段 {field_name} 已存在，跳过")
                    else:
                        print(f"添加字段 {field_name} 失败: {e}")
                        
        except Exception as e:
            print(f"添加字段时出错: {e}")
        
        # 3. 创建职业模板表
        print("\n3. 创建职业模板表...")
        create_class_template_sql = """
        CREATE TABLE IF NOT EXISTS character_class_templates (
            id INT AUTO_INCREMENT PRIMARY KEY COMMENT '职业ID',
            class_name VARCHAR(20) NOT NULL UNIQUE COMMENT '职业名称',
            class_name_en VARCHAR(20) NOT NULL COMMENT '职业英文名',
            description TEXT COMMENT '职业描述',
            base_hp INT NOT NULL DEFAULT 100 COMMENT '基础生命值',
            base_mp INT NOT NULL DEFAULT 50 COMMENT '基础魔法值',
            base_attack INT NOT NULL DEFAULT 10 COMMENT '基础攻击力',
            base_defense INT NOT NULL DEFAULT 5 COMMENT '基础防御力',
            base_speed INT NOT NULL DEFAULT 8 COMMENT '基础速度',
            hp_growth DECIMAL(3,1) NOT NULL DEFAULT 10.0 COMMENT '生命值成长',
            mp_growth DECIMAL(3,1) NOT NULL DEFAULT 5.0 COMMENT '魔法值成长',
            attack_growth DECIMAL(3,1) NOT NULL DEFAULT 2.0 COMMENT '攻击力成长',
            defense_growth DECIMAL(3,1) NOT NULL DEFAULT 1.0 COMMENT '防御力成长',
            speed_growth DECIMAL(3,1) NOT NULL DEFAULT 0.5 COMMENT '速度成长',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
            INDEX idx_class_name (class_name)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='角色职业模板表'
        """
        
        db_manager.execute_update(create_class_template_sql)
        print("职业模板表创建成功")
        
        # 4. 插入职业模板数据
        print("\n4. 插入职业模板数据...")
        insert_templates_sql = """
        INSERT IGNORE INTO character_class_templates 
        (class_name, class_name_en, description, base_hp, base_mp, base_attack, base_defense, base_speed,
         hp_growth, mp_growth, attack_growth, defense_growth, speed_growth) 
        VALUES 
        ('战士', 'warrior', '近战物理职业，拥有高生命值和防御力', 120, 30, 12, 8, 6, 15.0, 3.0, 3.0, 2.0, 0.3),
        ('法师', 'mage', '远程魔法职业，拥有高魔法值和魔法攻击', 80, 100, 8, 3, 7, 8.0, 12.0, 2.5, 0.5, 0.8),
        ('弓箭手', 'archer', '远程物理职业，拥有高敏捷和命中率', 100, 50, 10, 5, 10, 10.0, 5.0, 2.8, 1.2, 1.0),
        ('盗贼', 'rogue', '敏捷型职业，拥有高速度和暴击率', 90, 40, 11, 4, 12, 9.0, 4.0, 3.2, 0.8, 1.2),
        ('刺客', 'assassin', '敏捷型职业，拥有高速度和暴击率', 90, 40, 11, 4, 12, 9.0, 4.0, 3.2, 0.8, 1.2),
        ('牧师', 'priest', '辅助治疗职业，拥有治疗和辅助技能', 110, 80, 6, 6, 5, 12.0, 8.0, 1.5, 1.8, 0.2)
        """
        
        db_manager.execute_update(insert_templates_sql)
        print("职业模板数据插入成功")
        
        # 5. 验证修复结果
        print("\n5. 验证修复结果...")
        info = db_manager.get_table_info('characters')
        print("\n更新后的角色表结构:")
        for row in info:
            print(f"{row['Field']}: {row['Type']}")
            
        # 检查职业模板表
        template_query = "SELECT class_name, class_name_en, description FROM character_class_templates"
        templates = db_manager.execute_query(template_query)
        print("\n职业模板数据:")
        for template in templates:
            print(f"{template['class_name']} ({template['class_name_en']}): {template['description']}")
        
        print("\n数据库结构修复完成！")
        
    except Exception as e:
        print(f"修复数据库结构失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    fix_database_structure()